/**
 @Author Zhenglinbin
 @Date 2021/3/1
 **/
import {Props} from "@/components/typing";
import {useForm} from "@ant-design-vue/use/es/index";
import { clearForm, cloneForm } from '@/utils/form-util';

export const useFormHook = (formInfo: Props,rules: object) => {
    const { resetFields, validate, validateInfos, initialModel } = useForm(formInfo, rules);
    const fileds:Props = {}
    const defaultValue = getDefaultValue(formInfo);
    // 新增
    const add = (field?: string): void => {
        resetFields();
        clearForm(formInfo);
        cloneForm(formInfo, initialModel, field);
    };
    // 编辑
    const update = (info: Props, field?: string): void => {
        resetFields();
        cloneForm(formInfo, info, field);
    };
    const useAdd = () => {
        Object.keys(formInfo).forEach((key: string) => {
            if(formInfo[key] && typeof formInfo[key] !== 'object' && !Array.isArray(formInfo[key])) defaultValue.push(key)
            if(!defaultValue.includes(key)) fileds[key] = ''
        })
        resetFields(fileds);
    }
    const useResetFields = () => {
        resetFields(fileds);
    }
    const useSubmit = (e?: Event,columns?: string[]):Promise<boolean> => {
        return new Promise((resolve,reject) => {
            if(e) e.preventDefault();
            validate(columns).then(() => {
                resolve(true)
            }).catch(err => {
                reject(err)
            })
        })
    }
    const useUpdate = (info: Props) => {
        resetFields(fileds);
        const formModel: Props = info;
        if(formModel) {
            Object.keys(formModel).forEach(key => {
                formInfo[key] = formModel[key]
                if(!defaultValue.includes(key)) fileds[key] = ''
            })
        }
    }
    const assignment = (row: Props,target?: Props) => {
        let data = target ? target : row
        if(data && Object.keys(data).length > 0) {
            Object.keys(data).forEach(key => {
                formInfo[key] = data[key]
            })
        }
    }
    return {
        add,
        update,
        useAdd,
        useResetFields,
        useSubmit,
        useUpdate,
        assignment,
        validateInfos
    }
}

const getDefaultValue = (formInfo: Props):string[] => {
    const defaultValue:string[] = []
    if(formInfo) {
        Object.keys(formInfo).forEach((key: string) => {
            if((formInfo[key] || typeof formInfo[key] === 'boolean') && typeof formInfo[key] !== 'object' && !Array.isArray(formInfo[key])) defaultValue.push(key)
        })
    }
    return defaultValue
}
